/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.att.control;

import java.io.IOException;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;

/**
 *
 * @author lenovo
 */
public class AndroidProxy {
    
    private static AndroidProxy instance;
    private static IDevice device;
    
    static {
        instance = new AndroidProxy();
    }
    
    private AndroidProxy() {
        
    }
    
    public static synchronized AndroidProxy getInstance() {
        return instance;
    }
    
    private void waitForConnect(AndroidDebugBridge adb) throws InterruptedException {
        while (!adb.hasInitialDeviceList()) {
            Thread.sleep(100);
        }
    }
    
    public IDevice getDevice() {
        return device;
    }
    
    public void connection() throws InterruptedException {
    	AndroidDebugBridge.init(false);
		AndroidDebugBridge bridge = AndroidDebugBridge.createBridge();
        waitForConnect(bridge);
        IDevice[] devices = bridge.getDevices();
		for (IDevice dev : devices) {
			if (dev.getSerialNumber().equals(AttMain.sn)) {
				device = dev;
			}
		}
    }
    
    public void connectionWithMonkey() throws InterruptedException, TimeoutException, AdbCommandRejectedException, IOException {

		AndroidDebugBridge.init(false);
		AndroidDebugBridge bridge = AndroidDebugBridge.createBridge();
//    	AndroidDebugBridge adb = AndroidDebugBridge.createBridge();
        waitForConnect(bridge);
        IDevice[] devices = bridge.getDevices();
		for (IDevice dev : devices) {
			if (dev.getSerialNumber().equals(AttMain.sn)) {
				device = dev;
			}
		}
		connectMonkey(AttMain.action_port);
    }
    
    private static void connectMonkey (final int port) throws TimeoutException, AdbCommandRejectedException, IOException {
		device.createForward(port, port);
		Thread t = new Thread() {
			public void run() {
				String command = "monkey --port " + port;
				try {
					device.executeShellCommand(command, new OutputReceiver(), 0);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (TimeoutException e) {
					e.printStackTrace();
				} catch (AdbCommandRejectedException e) {
					e.printStackTrace();
				} catch (ShellCommandUnresponsiveException e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}
}
